#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
恩山论坛自动签到脚本
用于青龙面板环境变量: enshanck
"""
##cron: 48 10 * * *
##new Env("恩山论坛")
import requests
import os
import json
import sys

# 导入青龙通知模块
try:
    from notify import send
except ImportError:
    print("❌ 无法导入通知模块，请确保在青龙环境中运行")
    send = None

def main():
    # 从环境变量获取cookie
    cookie_env = os.getenv('enshanck')
    if not cookie_env:
        error_msg = "❌ 未找到环境变量 enshanck"
        print(error_msg)
        if send:
            send("恩山论坛", error_msg)
        sys.exit(1)
    
    # 解析cookie字符串为字典
    try:
        # 假设cookie是分号分隔的键值对
        cookies = {}
        for item in cookie_env.split(';'):
            if '=' in item:
                key, value = item.strip().split('=', 1)
                cookies[key] = value
    except Exception as e:
        error_msg = f"❌ Cookie解析失败: {e}"
        print(error_msg)
        if send:
            send("恩山论坛", error_msg)
        sys.exit(1)
    
    url = "https://www.right.com.cn/forum/plugin.php?id=erling_qd:action&action=sign"
    
    headers = {
        "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.200 Safari/537.36 HeyTapBrowser/51.8.8",
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Origin": "https://www.right.com.cn",
        "Referer": "https://www.right.com.cn/forum/erling_qd-sign_in.html",
        "Accept-Encoding": "gzip, deflate, br",
        "Accept-Language": "zh-CN,zh;q=0.9,en-US;q=0.8,en;q=0.7"
    }
    
    # 这里可能需要动态获取formhash，暂时使用示例值
    data = "formhash=a681793d"
    
    try:
        print("🚀 开始执行恩山论坛签到...")
        res = requests.post(url, headers=headers, cookies=cookies, data=data, timeout=10)
        
        # 打印响应状态
        print(f"📡 请求状态码: {res.status_code}")
        
        # 尝试解析响应
        try:
            result = res.json()
            credit = result.get("credit", 0)
            continuous_days = result.get("continuous_days", 0)
            message = result.get("message", "")
            
            # 判断是否为重复签到
            if credit == 0 and result.get("success"):
                repeat_msg = f"🔄 恩山论坛重复签到\n📅 连续签到天数: {continuous_days}\n💬 消息: {message}"
                print(repeat_msg)
                
                # 发送青龙通知
                if send:
                    send("恩山论坛", repeat_msg)
                
                # 青龙面板通知格式（控制台输出）
                print(f"🔔 {message} | 连续:{continuous_days}天")
                
            elif result.get("success"):
                success_msg = f"✅ 恩山论坛签到成功!\n🏆 获得恩山币: {credit}\n📅 连续签到天数: {continuous_days}\n💬 消息: {message}"
                print(success_msg)
                
                # 发送青龙通知
                if send:
                    send("恩山论坛", success_msg)
                
                # 青龙面板通知格式（控制台输出）
                print(f"🔔 {message} | 恩山币:{credit} 连续:{continuous_days}天")
            else:
                error_msg = result.get("message", "未知错误")
                full_error_msg = f"❌ 恩山论坛签到失败: {error_msg}\n📄 完整响应: {res.text}"
                print(full_error_msg)
                
                # 发送青龙通知
                if send:
                    send("恩山论坛", full_error_msg)
                
        except json.JSONDecodeError:
            error_msg = f"❌ 响应不是有效的JSON格式\n📄 响应内容: {res.text}"
            print(error_msg)
            if send:
                send("恩山论坛", error_msg)
            
    except requests.exceptions.RequestException as e:
        error_msg = f"❌ 网络请求失败: {e}"
        print(error_msg)
        if send:
            send("恩山论坛", error_msg)
        sys.exit(1)
    except Exception as e:
        error_msg = f"❌ 程序执行异常: {e}"
        print(error_msg)
        if send:
            send("恩山论坛", error_msg)
        sys.exit(1)

if __name__ == "__main__":
    main()